package com.lwc.geojson.mapper;


import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.lwc.geojson.entity.SystemGeo;
import org.apache.ibatis.annotations.*;

/**
 * SystemGeo 数据库操作Mapper
 *
 * @author luwc
 * @time 2025-04-19 22:10:43
 */

@Mapper
public interface SystemGeoMapper extends BaseMapper<SystemGeo> {

    // 基础插入（使用TypeHandler自动转换Geometry）
    @Override
    int insert(SystemGeo entity);

    // 使用WKT格式插入
    @Insert("INSERT INTO cfdns_system_geo " +
            "(adcode, name, center_lon, center_lat, boundary, " +
            "bbox_min_lon, bbox_max_lon, bbox_min_lat, bbox_max_lat, " +
            "creator_id, created_at) " +
            "VALUES (#{adcode}, #{name}, #{centerLon}, #{centerLat}, " +
            "ST_GeomFromText(#{boundaryWkt}), " +
            "#{bboxMinLon}, #{bboxMaxLon}, #{bboxMinLat}, #{bboxMaxLat}, " +
            "#{creatorId}, NOW())")
    int insertWithWkt(SystemGeo entity);

    // 空间查询（查找包含某点的记录）
    @Select("SELECT * FROM cfdns_system_geo " +
            "WHERE ST_Contains(boundary, ST_GeomFromText(#{pointWkt}, 4326)) = 1 " +
            "AND deleted = 0")
    SystemGeo selectContainsPoint(@Param("pointWkt") String pointWkt);

    // 获取WKT格式的边界
    @Select("SELECT id, adcode, name, ST_AsText(boundary) as boundaryWkt " +
            "FROM cfdns_system_geo WHERE adcode = #{adcode} AND deleted = 0")
    SystemGeo selectWithWktByAdcode(@Param("adcode") String adcode);

    // 更新边界数据
    @Update("UPDATE cfdns_system_geo SET " +
            "boundary = ST_GeomFromText(#{boundaryWkt}, 4326), " +
            "center_lon = #{centerLon}, center_lat = #{centerLat}, " +
            "bbox_min_lon = #{bboxMinLon}, bbox_max_lon = #{bboxMaxLon}, " +
            "bbox_min_lat = #{bboxMinLat}, bbox_max_lat = #{bboxMaxLat}, " +
            "updater_id = #{updaterId}, updated_at = NOW() " +
            "WHERE id = #{id} AND deleted = 0")
    int updateBoundary(SystemGeo entity);

    // 逻辑删除
    @Update("UPDATE cfdns_system_geo SET " +
            "deleted = 1, deleted_at = NOW(), updater_id = #{userId} " +
            "WHERE id = #{id} AND deleted = 0")
    int logicDeleteById(@Param("id") Long id, @Param("userId") Long userId);
}
